<template>
  <div class="register-container">
    <div class="register_box">
      <!--头像区域-->
      <div class="avatar_box">
        <img src="../assets/timg.png"
             alt="图片不见了">
      </div>
      <!--注册表单区域-->
      <el-form label-width="70px"
               class="register_form"
               :model="registerForm"
               ref="registerFromRef"
               :rules="registerFromRules">
        <!--姓名-->
        <el-form-item prop="username"
                      label="姓名">
          <el-input v-model="registerForm.username"></el-input>
        </el-form-item>
        <!--学号-->
        <el-form-item prop="studentNumber"
                      label="学号">
          <el-input v-model="registerForm.studentNumber"></el-input>
        </el-form-item>
        <el-form-item prop="password"
                      label="密码">
          <el-input v-model="registerForm.password"
                    type="password"></el-input>
        </el-form-item>
        <el-form-item prop="Cpassword"
                      label="确认密码">
          <el-input v-model="registerForm.Cpassword"
                    type="password"
                    :disabled="registerForm.password===''? true:false"></el-input>
        </el-form-item>
        <el-form-item prop="email"
                      label="邮箱">
          <el-input v-model="registerForm.email"></el-input>
        </el-form-item>
        <!--按钮-->
        <el-form-item prop="code"
                      label="验证码">
          <el-input v-model="registerForm.code"></el-input>

        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     class="code"
                     round
                     :disabled="btnDisabled"
                     @click="code">获取验证码</el-button>
          <span class="status">{{timeCount}}</span>
        </el-form-item>
        <el-form-item>
          <el-button type="success"
                     class="register"
                     @click="register">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="stars">
      <div class="star"
           v-for="(item, index) in starsCount"
           :key="index"
           ref="star"></div>
    </div>
  </div>
</template>

<script>
import CryptoJS from 'crypto-js'
export default {
  name: 'Register',
  data () {
    // 验证性别是否男或女
    var passWord = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
      } else {
        const reg = /^(?![^a-zA-Z]+$)(?!\D+$)/
        if (reg.test(value)) {
          callback()
        } else {
          callback(new Error('密码格式必须为6-18位字母、数字'))
        }
      }
    }
    var checkPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
      } else {
        if (value !== this.registerForm.password) {
          callback(new Error('与前面输入的密码不一致，请重新输入'))
        } else {
          callback()
        }
      }
    }
    return {
      // 按钮禁用
      btnDisabled: false,
      // 登录表单的数据绑定对象
      registerForm: {
        username: '',
        studentNumber: '',
        password: '',
        Cpassword: '',
        email: '',
        code: ''
      },
      // 表单验证
      registerFromRules: {
        username: [
          { required: true, message: '请输入名字', trigger: 'blur' }
        ],
        studentNumber: [
          { required: true, message: '请输入学号', trigger: 'blur' },
          { max: 12, min: 12, message: '学号必须是11位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: passWord, trigger: 'blur' }
        ],
        Cpassword: [
          { required: false, message: '请确认密码', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      timeCount: '',
      starsCount: 800,
      distance: 800
    }
  },
  methods: {
    async code () {
      let username
      let email
      // 这里validateField验证通过后结果是false
      this.$refs.registerFromRef.validateField('username', valid => {
        username = valid
      })
      this.$refs.registerFromRef.validateField('email', valid => {
        email = valid
      })
      if (!username && !email) {
        const { data: res } = await this.$axios.post('/users/verify', {
          username: this.registerForm.username,
          email: this.registerForm.email
        }
        )
        if (res.meta.code !== 0) {
          this.$message.error(res.meta.msg)
        } else {
          this.$message.success(res.meta.msg)
          // 验证码倒计时
          let timeCount = 60
          const time = setInterval(() => {
            timeCount--
            this.btnDisabled = true
            this.timeCount = timeCount
            if (timeCount === 0) {
              clearInterval(time)
              this.timeCount = ''
              this.btnDisabled = false
            }
          }, 1000)
        }
      } else {
        this.$message.warning('请正确填写表单')
      }
    },
    register () {
      this.$refs.registerFromRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$axios.post('/users/signup', {
          username: this.registerForm.username,
          studentNum: this.registerForm.studentNumber,
          password: CryptoJS.MD5(this.registerForm.pwd).toString(),
          email: this.registerForm.email,
          code: this.registerForm.code.toUpperCase()
        })
        console.log(res)
        if (res.code !== 0) {
          this.$message.warning(res.msg)
          return false
        } else {
          this.$message.success(res.msg)
          this.$router.push('/login')
        }
      })
    }
  },
  mounted () {
    const starArr = this.$refs.star
    starArr.forEach(item => {
      const speed = 0.2 + (Math.random() * 1)
      const thisDistance = this.distance + (Math.random() * 300)
      item.style.transformOrigin = `0 0 ${thisDistance}px`
      item.style.transform = `translate3d(0, 0, -${thisDistance}px) rotateY(${(Math.random() * 360)}deg) rotateX(${(Math.random() * -50)}deg) scale(${speed}, ${speed})`
    })
  }
}
</script>
<style lang="less" scoped>
@keyframes rotate {
  0% {
    transform: perspective(400px) rotateZ(20deg) rotateX(-40deg) rotateY(0);
  }
  100% {
    transform: perspective(400px) rotateZ(-20deg) rotateX(40deg)
      rotateY(-360deg);
  }
}
.stars {
  transform: perspective(500px);
  transform-style: preserve-3d;
  position: absolute;
  perspective-origin: 50% 100%;
  left: 50%;
  animation: rotate 100s infinite linear;
  bottom: 0;
}
.star {
  width: 2px;
  height: 2px;
  background: #f7f7b8;
  position: absolute;
  top: 0;
  left: 0;
  backface-visibility: hidden;
}

.register-container {
  background: -webkit-linear-gradient(
    top,
    rgb(0, 0, 0) 50%,
    rgb(25, 19, 39) 80%,
    rgb(43, 32, 72)
  );
  overflow: hidden;
  height: 100%;
  .register_box {
    // 注册界面居中
    width: 500px;
    height: 580px;
    background: -webkit-linear-gradient(
      top,
      rgb(0, 0, 0) 50%,
      rgb(25, 19, 39) 80%,
      rgb(43, 32, 72)
    );
    opacity: 0.9;
    // 设置圆角
    border-radius: 10px;
    position: relative;
    // 距离左上各距离50%
    left: 50%;
    top: 100px;
    // 横轴纵轴偏移50%
    transform: translateX(-50%);
    display: flex;
    flex-direction: column;

    .avatar_box {
      height: 130px;
      width: 130px;
      // 添加边框
      border: 1px solid #eee;
      // 变宽变成圆角
      border-radius: 50%;
      padding: 10px;
      // 给外边款家阴影
      box-shadow: 0 0 10px #ddd;
      // 将这个盒子放置于主盒子正上方
      position: absolute;
      left: 56%;
      // 再移动图片自身的﹣50%,横向和纵向（左边和上边）是根据avatar_box来移动，也就是65px
      transform: translate(-50%, -50%);
      background: -webkit-linear-gradient(
        top,
        rgb(0, 0, 0) 50%,
        rgb(25, 19, 39) 80%,
        rgb(43, 32, 72)
      );
      // 让图片的宽和高等于副盒子的宽高
      img {
        width: 100%;
        height: 100%;
        //图片也变为圆角
        border-radius: 50%;
        background-color: #eee;
      }
    }
    .register_form {
      position: absolute;
      top: 90px;
      bottom: 0;
      width: 100%;
      padding: 0 20px;
      //不让账号密码栏超出register-contain外面
      box-sizing: border-box;
      .el-form-item {
        /deep/ .el-form-item__label {
          color: #666666;
          font-weight: 600;
        }
        span {
          position: absolute;
          right: 30%;
          font-size: 0.8em;
          color: red;
        }
        .code {
          // 让按钮居右对其
          float: right;
          font-size: 12px;
        }
        .register {
          position: absolute;
          left: 0;
          margin-left: 120px;
        }
      }
    }
  }
}
</style>
